<template>
  <el-card class="full-card">
    <h2 class="page-title">轮播图管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" label-width="100px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="标题">
            <el-input v-model.trim="queryParams.title" placeholder="请输入标题" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="success" @click="openDialog('create')">新建轮播图</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin: 20px 0">
      <el-table-column label="图片" width="150px">
        <template #default="{ row }">
          <el-image
              :src="row.imageUrl"
              fit="cover"
              style="width: 100px; height: 50px"
              :preview-src-list="[row.imageUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="200px" />
      <el-table-column prop="description" label="描述" min-width="200px" />
      <el-table-column prop="sortOrder" label="排序" width="80px" />
      <el-table-column prop="status" label="状态" width="100px">
        <template #default="{ row }">
          <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template #default="{ row }">
          <el-button @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20]"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        class="pagination"
    />

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        :close-on-click-modal="false"
        @close="resetForm"
    >
      <el-form
          :model="formData"
          label-width="100px"
          ref="formRef"
          :rules="rules"
          class="dialog-form"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="formData.title" placeholder="请输入轮播图标题" />
        </el-form-item>

        <el-form-item label="图片上传" prop="imageUrl">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
          >
            <el-image
                v-if="formData.imageUrl"
                :src="formData.imageUrl"
                fit="cover"
                class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
              v-model.trim="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入简要描述"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
              v-model="formData.sortOrder"
              :min="1"
              :max="999"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import adminApi from '../../apis/adminAPi.js'
import type { UploadProps } from 'element-plus'

const queryParams = reactive({
  currentPage: 1,
  pageSize: 5,
  title: '',
  status: null
})

const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: null,
  title: '',
  imageUrl: '',
  description: '',
  sortOrder: 1,
  status: 1
})

// 验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 50, message: '最多50个字符', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { max: 200, message: '最多200个字符', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 上传配置
const uploadUrl = 'http://localhost:88/File/upImg' // 替换为实际上传地址
const uploadHeaders = {
  // 如果需要认证token可以在这里添加
  // Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 初始化数据
const fetchData = async () => {
  try {
    const res = await adminApi.getAllCarousels(queryParams)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.currentPage = 1
  fetchData()
}

// 重置搜索
const resetQuery = () => {
  queryParams.title = ''
  queryParams.status = null
  fetchData()
}

// 打开对话框
const openDialog = (type = 'create', row = null) => {
  if (row && type === 'edit') {
    Object.assign(formData, {
      id: row.id,
      title: row.title,
      imageUrl: row.imageUrl,
      description: row.description,
      sortOrder: row.sortOrder,
      status: row.status
    })
  }
  dialogTitle.value = type === 'create' ? '新建轮播图' : '编辑轮播图'
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    title: '',
    imageUrl: '',
    description: '',
    sortOrder: 1,
    status: 1
  })
  formRef.value?.clearValidate()
}

// 图片上传成功回调
const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 200) {
    formData.imageUrl = response.data
    formRef.value?.clearValidate('imageUrl')
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG 格式图片')
    return false
  }
  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const apiMethod = formData.id
        ? adminApi.updateCarousel
        : adminApi.addCarousel

    const res = await apiMethod(formData)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      fetchData()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 编辑操作
const handleEdit = (row) => {
  openDialog('edit', row)
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await adminApi.deleteCarousel({ id: row.id })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    const res = await adminApi.updateCarousel({
      id: row.id,
      status: row.status
    })
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchData()
}

// 初始化数据
fetchData()
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 80px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 150px;
  height: 80px;
  object-fit: cover;
}

.full-card {
  margin: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.dialog-form {
  padding: 0 20px;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}
</style>
